package com.kot.backend.consumer.utils;

import com.alibaba.fastjson2.JSONObject;
import com.kot.backend.consumer.WebSocketServer;
import com.kot.backend.mapper.BotMapper;
import com.kot.backend.pojo.Bot;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BotStep extends Thread{

    private Integer hostId;
    private Integer opponentId;
    private Bot bot;
    private Boolean tag;
    private Integer d=0;

    private final static String addBotUrl = "http://127.0.0.1:3002/bot/add/";//发给botrunningsystem的url



    private void sendBotCode() {//判断是否要执行代码，并把代码发给botrunningsystem


        MultiValueMap<String, String> data = new LinkedMultiValueMap<>();//必须是这个哈希表
        data.add("user_id", hostId.toString());//传递的参数
        data.add("bot_code", bot.getContent());

        String model = WebSocketServer.users.get(hostId).model;
        data.add("input", model);//这是一个辅助函数
        System.out.println("model"+model);
        WebSocketServer.restTemplate.postForObject(addBotUrl, data, String.class);//向botrunningsystem发送信息
    }



    @Override
    public void run() {
        while (tag){

            sendBotCode();

//            System.out.println("每隔2秒获取的方向是："+d);

//            System.out.println(hostId+"****"+opponentId);
            //把自己ai的方向传给本方玩家(前端同时发射子弹)
            JSONObject respHost = new JSONObject();//A操作完后，把操作传递给B
            respHost.put("event", "myAImove");//确定信息类型
            respHost.put("direction", d);
            respHost.put("status","move");
            if(WebSocketServer.users.get(hostId)!=null)
                WebSocketServer.users.get(hostId).sendMessage(respHost.toJSONString());

            JSONObject respOp = new JSONObject();//A操作完后，把操作传递给B

            respOp.put("event", "opAImove");//确定信息类型
            respOp.put("direction", d);
            respOp.put("status","move");
            if(WebSocketServer.users.get(opponentId)!=null){
                WebSocketServer.users.get(opponentId).sendMessage(respOp.toJSONString()); //用这个链接将信息传回给前端（在这里发送信息）
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
